package com.itsu.spbspider.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itsu.spbspider.entity.Crawler;
import com.itsu.spbspider.entity.Job;
import com.itsu.spbspider.entity.News;
import com.itsu.spbspider.entity.User;
import com.itsu.spbspider.service.CrawlerService;
import com.itsu.spbspider.service.JobService;
import com.itsu.spbspider.service.NewsService;
import com.itsu.spbspider.service.UserService;
import com.itsu.spbspider.util.EncryptUtil;
import com.itsu.spbspider.util.ProjectUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@Slf4j
public class MyController {
    @Resource
    UserService userService;

    @Resource
    JobService jobService;

    @Resource
    CrawlerService crawlerService;

    @Resource
    NewsService newsService;

    @PostMapping("/login.do")
    public String login(User user, HttpServletRequest request, HttpServletResponse response, Model model) throws Exception {
        boolean rem = user != null ? user.isRem() : false;
        user = userService.login(user);
        if (user != null) {
            if (rem) {
                Cookie cookie = new Cookie("user", EncryptUtil.encrypt(user.getUsername()) + "-=-" + user.getPassword());
                cookie.setMaxAge(60 * 60 * 24 * 7);
                cookie.setPath("/");
                response.addCookie(cookie);
            }
            request.getSession().setAttribute("user", user);
            return "redirect:/index";
        } else {
            model.addAttribute("errorMsg", "用户名或密码错误");
            return "login";
        }
    }


    @GetMapping("/data/joblist")
    @ResponseBody
    public Map jobList(Integer page, Integer limit) throws Exception {
        Map map = new HashMap();
        Page jobPage = jobService.getJobList(page, limit);
        map.put("code", 0);
        map.put("msg", "success");
        map.put("count", jobPage.getTotal());
        map.put("data", jobPage.getRecords());
        return map;
    }

    @GetMapping("/paramsSetting/{crawlerId}")
    public String toJobSetting(@PathVariable("crawlerId") Integer crawlerId, Model model) throws Exception {

        Crawler crawler = crawlerService.getCrawlerById(crawlerId);
        model.addAttribute("crawler", crawler);
        return "paramsSetting";
    }

    @PutMapping("/paramsSetting/update")
    @ResponseBody
    public Map updateJobSetting(@RequestBody Crawler crawler) throws Exception {
        Map map = new HashMap();
        crawlerService.updateCrawler(crawler);
        map.put("code", 0);
        map.put("msg", "ok");
        return map;

    }

    @GetMapping("/logout")
    @ResponseBody
    public String logOut(HttpServletRequest request, HttpServletResponse response) {
        request.getSession().setAttribute("user", null);
        request.getSession().invalidate();
        Cookie[] cookies = request.getCookies();
        if (cookies != null && cookies.length > 0) {
            for (Cookie cookie : cookies) {
                cookie.setMaxAge(0);
                cookie.setValue(null);
                cookie.setPath("/");
                response.addCookie(cookie);
            }
        }
        return "ok";
    }

    @GetMapping("/jobSetting/{id}")
    public String toExecuteSettingPage(@PathVariable("id") String id, Model model) throws Exception {
        Job job = jobService.getJobById(id);
        model.addAttribute("job", job);
        return "jobSetting";
    }

    @PutMapping("/updatejob")
    @ResponseBody
    public Map updateJob(@RequestBody Job job) throws Exception {
        Map map = new HashMap();
        job.setTimeInterval(ProjectUtil.caculateSeconds(job));
        jobService.updateJob(job);
        map.put("code", 0);
        map.put("msg", "ok");
        return map;
    }

    @GetMapping("/newsList/{page}/{jobName}")
    @ResponseBody
    public Map getNewsList(@PathVariable("page") Integer page, @PathVariable("jobName") String jobName) throws Exception {
        Map map = new HashMap();
        IPage<News> iPage = null;
        if (StringUtils.isBlank(jobName) || "all".equals(jobName) || "null".equals(jobName)) {
            iPage = newsService.getByPage(page, 20);
        } else {
            iPage = newsService.getByJobNamePage(page, 20, jobName);
        }
        List<News> newsList = iPage.getRecords();
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        for (News news : newsList) {
            if (StringUtils.isNotBlank(news.getTs()))
                news.setTs(sf.format(Long.valueOf(news.getTs())));
        }
        map.put("code", 0);
        map.put("data", newsList);
        map.put("total", iPage.getPages());
        return map;
    }

    @PostMapping("/addJob.do")
    @ResponseBody
    public Map addNewJob(@RequestBody Map params) throws Exception {
        Map map = new HashMap();
        jobService.addNewJob(params);
        map.put("code", 0);
        map.put("msg", "ok");
        return map;
    }

    @GetMapping("/datapre.html")
    public String toDataPre(Model model) throws Exception {
        List<String> jobNames = jobService.getJobModels();
        model.addAttribute("jobNames", jobNames);
        return "datapre";
    }

    @DeleteMapping("/delJob/{jobId}")
    @ResponseBody
    public Map delJob(@PathVariable("jobId") String jobId) throws Exception {
        Map map = new HashMap();
        jobService.delteJobById(jobId);
        map.put("code", 0);
        map.put("msg", "ok");
        return map;
    }

    @PostMapping("/resetpwd.do")
    @ResponseBody
    public Map resetPwd(@RequestBody Map params) throws Exception {
        Map map = new HashMap();
        userService.resetPwd(params);
        map.put("code", 0);
        return map;
    }
}
